/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.tang.tframe.sdm.web.shiro.realm;

import cn.tang.tframe.common.base.BaseResult;
import cn.tang.tframe.sdm.web.shiro.BaseQtucAuthenticationToken;
import cn.tang.tframe.sdm.web.shiro.IWebTokenService;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

public class BaseQtucShiroRealm<PK extends Serializable,TK extends BaseQtucAuthenticationToken> extends AbstractQtucShiroRealm<PK,TK> implements InitializingBean {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected IWebTokenService<PK> webTokenService;

	@Override
	protected IShiroUser<PK> retriveFromToken(TK token) {
		if (null == token) {
			logger.error("no token when login");
			throw new AuthenticationException("登录信息有误");
		}

		BaseShiroUser ssoShiroUser = new BaseShiroUser();
		ssoShiroUser.setToken(token.getSsoToken());
		ssoShiroUser.setUid(readUidByToken(token.getSsoToken()));
		return ssoShiroUser;
	}
	protected PK readUidByToken(String token){
		BaseResult<PK> readUidByToken = webTokenService.readUidByToken(token);
		if(null == readUidByToken || !readUidByToken.getSuccess() || null == readUidByToken.getModel()){
			logger.error("read token fail when login");
			throw new AuthenticationException("登录信息有误");
		}
		return readUidByToken.getModel();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.setAuthenticationTokenClass(BaseQtucAuthenticationToken.class);
	}
}
